<?php
/**
 * 七牛上传扩展
 */
namespace app\admin\event;

class Qiniu{

    private $auth;
    //需要上传的空间
    private $bucket;
    //访问链接
    private $url;
    /**
     * 配置
     * @param  [type] $miye   密钥
     * @param  string $bucket 七牛空间
     * @return [type]         [description]
     */
    public function __construct(){
        $qiniu = C('qiniu');
        $this->set_conf($qiniu);
        $this->bucket = $qiniu['bucket'];
        $this->url = $qiniu['url'];
    }

    public function set_conf($qiniu){
        require VENDOR_PATH.'qiniu/autoload.php';
        \think\Loader::addNamespace('Qiniu',VENDOR_PATH.'Qiniu/');
        $this->auth = new \Qiniu\Auth($qiniu['accessKey'], $qiniu['secretKey']);
    }

    /**
     * 上传
     * 上传文件路径，文件名
     */
    public function upload($filePath,$key=''){
        //生成要上传的token
        $token = $this->auth->uploadToken($this->bucket);

        //文件名
        $key = $key.date('YmdHis',time()).'_'.rand(1,999).'.jpg';

        $uploadMgr = new \Qiniu\Storage\UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            $ret['key'] = $this->url.$ret['key'];
            return $ret;
        }
    }

    //文件删除
    public function delete($key){
        $bucketManager = new \Qiniu\Storage\BucketManager($this->auth);
        return $bucketManager->delete($this->bucket,$key);
    }
}
